import {Image, StyleSheet, View, Text, TouchableOpacity, ImageBackground, FlatList, Animated, RefreshControl, ActivityIndicator} from 'react-native';
import {Stack, useRouter} from "expo-router";
import { scaleSize } from "@/utils/screenSize"
import AntDesign from '@expo/vector-icons/AntDesign';
import { Ionicons } from '@expo/vector-icons';
import {useEffect, useState} from "react";
import addressIcon from "@/assets/images/collection/address.png"
import dateTimeIcon from "@/assets/images/collection/dateTime.png"
import empty_icon from "@/assets/images/concern/empty_fan.png"
import activityTag from "@/assets/images/collection/activityTag.png"

export default function collectionScreen() {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [refreshing, setRefreshing] = useState(false);
    const [triggerRefresh, setTriggerRefresh] = useState(false);
    const [page, setPage] = useState(1);
    const [refreshingText, setRefreshingText] = useState('下拉刷新');
    const scrollY = new Animated.Value(0); // 用于跟踪滚动偏移

    const router = useRouter();

    const goActivityDetail = function () {
        router.push("/")
    };

    // 自定义加载图标组件
    const RefreshControlHeader = ({ refreshing, text }) => (
        refreshing &&  <View style={styles.refreshHeader}>
            {/*{refreshing && <Image source={require('./path/to/your/loading-icon.gif')} style={styles.refreshIcon} />} /!* 替换为你的加载图标 *!/*/}
            <Text style={styles.refreshText}>{text}</Text>
        </View>
    );

    // 初次加载数据
    useEffect(() => {
        loadMoreData();
    }, []);

    useEffect(() => {
        if (triggerRefresh) {
            handleRefresh();
            setTriggerRefresh(false); // Reset trigger
        }
    }, [triggerRefresh]);

    const loadMoreData = () => {
        if (loading) return;

        setLoading(true);
        // 模拟网络请求来获取更多数据
        setTimeout(() => {
            const newData = Array.from({ length: 10 }, (_, index) => `Item ${page * 10 + index + 1}`);
            setData((prevData) => [...prevData, ...newData]);
            setPage((prevPage) => prevPage + 1);
            setLoading(false);
        }, 100);
    };

    const handleRefresh = () => {
        setRefreshing(true);
        setRefreshingText('正在刷新...');
        setPage(1);

        // 模拟网络请求来获取新数据
        setTimeout(() => {
            const newData = Array.from({ length: 10 }, (_, index) => `Item ${index + 1}`);
            setData(newData);
            setRefreshing(false);
            setRefreshingText('下拉刷新');
        }, 100);
    };

    const renderFooter = () => {
        if (!loading) return null;
        if (data.length <= 0) return null;
        return (
            <View style={{ paddingVertical: 10, flexDirection: "row", justifyContent: "center", alignItems: "center" }}>
                <ActivityIndicator size="small" />
                <Text style={{ textAlign: 'center', fontSize: 14, color: "#676978", marginLeft: 5, }}>疯狂加载中</Text>
            </View>
        );
    };

    const handleScroll = Animated.event(
        [{ nativeEvent: { contentOffset: { y: scrollY } } }],
        {
            useNativeDriver: false,
            listener: event => {
                const offsetY = event.nativeEvent.contentOffset.y;

                if (!refreshing) {
                    // 根据下拉距离更新文本
                    if (offsetY < -100) {
                        setRefreshingText('松开刷新'); // 超过 -100 的偏移量显示松开刷新
                    } else if (offsetY < 0) {
                        setRefreshingText('下拉刷新'); // 在 -100 到 0 之间时显示下拉刷新
                    }
                }
            },
        }
    );

    const onScrollEnd = () => {
        scrollY.addListener(({ value }) => {
            if (!refreshing && value < -100) {
                setTriggerRefresh(true); // 触发刷新
            }
        });
    };

    const ActivityItem = () => {
        return (
            <View style={styles.activityContainer}>
                <View style={styles.activitybody}>
                    <View style={styles.activityBanner}>
                        <Image source={empty_icon} style={{ width: "100%", height: "100%" }} />
                        <ImageBackground source={activityTag} style={styles.activityTagWarp}>
                            <Text style={styles.tagText}>娱乐</Text>
                        </ImageBackground>

                    </View>
                    <View style={styles.activityContent}>
                        <View style={styles.activityTitleWarp}>
                            <Text
                                style={styles.activityTitle}
                                numberOfLines={2}
                                ellipsizeMode="tail"
                            >周末去露营去嗨p末去</Text>
                        </View>
                        <View style={styles.activityTag}>
                            <Text style={styles.activityTagText}>交友</Text>
                        </View>
                        <View style={styles.activityDateWarp}>
                            <View style={styles.addressIcon}>
                                <Image source={dateTimeIcon} style={{ width: '100%', height: "100%" }} />
                            </View>
                            <Text style={ styles.activityDate }>10.15 18:00-22:00</Text>
                        </View>
                        <View style={styles.activityAdressWarp}>
                            <View style={styles.addressIcon}>
                                <Image source={addressIcon} style={{ width: '100%', height: "100%" }} />
                            </View>
                            <Text style={styles.activityAdress}>广州市琶洲暴力世贸101</Text>
                        </View>
                    </View>
                </View>
                <View style={styles.activityFooter}>
                    <View style={styles.joinList}>
                        <View style={styles.joinListWarp}>
                            <View style={styles.joinAvator}>

                            </View>
                            <View style={[styles.joinAvator,styles.maLeft]}>
                            </View>
                            <View style={[styles.joinAvator,styles.maLeft]}>
                            </View>
                            <View style={[styles.joinAvator,styles.maLeft]}>
                            </View>
                        </View>
                        <View style={styles.joinContent}>
                            <Text style={styles.joinContentText}>正在招募...</Text>
                        </View>
                    </View>
                    <View style={styles.activityMoney}>
                        <Text style={styles.activityMoneyText}>¥30</Text>
                    </View>
                </View>
            </View>
        )
    };



    return (
        <View style={{ height: "100%", backgroundColor: "#F7F7F7" }}>
            <Stack.Screen
                options={{
                    title: '我的收藏', // 设置屏幕标题
                    headerStyle: {
                        backgroundColor: '#f7f7f7', // 设置标题栏的背景颜色
                    },
                    headerShadowVisible: false, // 隐藏底部阴影和边框
                    headerBackTitleVisible: false,
                    headerTintColor: "#333",
                    headerLeft: () => (
                        <TouchableOpacity onPress={() => router.back()}>
                            <AntDesign name="left" size={19} color="#333" />
                            {/*<Ionicons name="arrow-back" size={30} color="#fff" style={{ paddingLeft: 15 }} />*/}
                        </TouchableOpacity>
                    ),
                }}
            />
            <FlatList
                data={data}
                renderItem={({ item }) => <ActivityItem/>}
                keyExtractor={(item, index) => index.toString()}
                onEndReached={loadMoreData}
                onEndReachedThreshold={0.5} // 当滚动到距离底部还有50%的时候触发
                ListFooterComponent={renderFooter}
                refreshControl={
                    <RefreshControl
                        refreshing={refreshing}
                        // onRefresh={handleRefresh} // 绑定刷新函数
                        title={refreshing ? '' : refreshingText} // 在正在刷新状态时不显示文本
                        titleColor="#333" // 设置提示文字颜色
                        tintColor="transparent" // 隐藏刷新指示器
                    />
                }
                onScroll={handleScroll}
                onScrollEndDrag={onScrollEnd}
                ListHeaderComponent={<RefreshControlHeader refreshing={refreshing} text={refreshingText} />}
            />
        </View>
    );
}

const styles = StyleSheet.create({
    activityContainer: {
        // flexDirection: "row",
        marginLeft: 12,
        marginRight: 12,
        height: scaleSize(164),
        backgroundColor: "#fff",
        borderRadius: 8,
        marginBottom: 12,
    },
    activitybody: {
        padding: 12,
        flexDirection: "row",

    },
    activityBanner: {
        position: "relative",
        width: scaleSize(110),
        height: scaleSize(110),
        backgroundColor: "blue",
        borderRadius: 4,
    },
    activityContent: {
        marginLeft: 10,
    },
    activityTitleWarp: {
        width: scaleSize(192),
    },
    activityTitle: {
        fontSize: 16,
        fontWeight: "bold",
        color: "#2A2B30",
        letterSpacing: 1.2,
        lineHeight: 22,
    },
    addressIcon: {
        width: scaleSize(11),
        height: scaleSize(11),
    },
    activityTag: {
        width: scaleSize(28),
        height: scaleSize(12),
        backgroundColor: "rgba(255,70,0,0.1)",
        borderRadius: 10,
        marginTop: 6,
    },
    activityTagText: {
        fontSize: 8,
        color: "#EC6138",
        textAlign: "center",
        lineHeight: 12,
    },
    activityDateWarp: {
        flexDirection: "row",
        alignItems: "center",
        marginTop: 6,
        marginBottom: 6,
    },
    activityDate: {
        marginLeft: 3,
        fontSize: 12,
        color: "#676978"
    },
    activityAdressWarp: {
        flexDirection: "row",
        alignItems: "center",
    },
    activityAdress: {
        fontSize: 12,
        color: "#676978",
        marginLeft: 3,
    },
    joinList: {
        flexDirection: "row",
        alignItems: "center",
    },
    activityFooter: {
        flexDirection: "row",
        paddingLeft: 12,
        paddingRight: 12,
        justifyContent: "space-between",
       alignItems: "center"
    },
    joinAvator: {
        width: scaleSize(20),
        height: scaleSize(20),
        backgroundColor: "red",
        borderRadius: 10,
        borderColor: "#fff",
        borderWidth: 1,
    },
    maLeft: {
        marginLeft: -7,
    },
    joinListWarp: {
        flexDirection: "row",
    },
    joinContent: {
        marginLeft: 10,
    },
    joinContentText: {
        color: "#333",
        fontSize: 12,
        fontWeight: "bold"
    },
    activityMoney: {
        width: 56,
        height: 24,
        backgroundColor: "#EC6138",
        borderRadius: 12,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center"
    },
    activityMoneyText: {
        color: "#fff",
        fontSize: 18,
    },
    activityTagWarp: {
        position: "absolute",
        width: 30,
        height: 20,
        // backgroundColor: "red",
    },
    tagText: {
        fontSize: 10,
        textAlign: "center",
        color: "#fff",
        marginTop: 1,
    },
    refreshHeader: {
        alignItems: 'center',
        padding: 20,
    },
    refreshIcon: {
        width: 12,
        height: 12,
        marginBottom: 10,
    },
    refreshText: {
        fontSize: 12,
        color: '#333',
    },
});
